package cn.edu.sdjzu.mocige_server.controller;

import cn.edu.sdjzu.mocige_server.common.api.Result;
import cn.edu.sdjzu.mocige_server.entity.User;
import cn.edu.sdjzu.mocige_server.service.UserService;
import cn.edu.sdjzu.mocige_server.service.jwt.JwtService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtService jwtService;
    @PostMapping("/login")
    public Result<?> login(@RequestBody User loginUser) {
        User user = userService.getUserByUsername(loginUser.getUsername());
        //打印出user在控制台
        log.info("loginUser: {}", loginUser);
        log.info("user: {}", userService.getAllUsers());

        if (user != null && userService.verifyPassword(user.getUsername(), loginUser.getPasswordHash())) {
            String token = jwtService.generateToken(user.getUsername());
            return Result.success(new AuthResponse(token, user));
        }
        return Result.failed("用户名或密码错误");
    }
    static class AuthResponse {
        private String token;
        private User user;
        public AuthResponse(String token, User user) {
            this.token = token;
            this.user = user;
        }

        public String getToken() {
            return token;
        }

        public User getUser() {
            return user;
        }
    }
}
